﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Migrations;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Terminal;
using com.nm.library.Helper;
using NHibernateVertica;
using Senparc.Weixin.Helpers.Extensions;
using Senparc.Weixin.Work.AdvancedAPIs;
using Senparc.Weixin.Work.AdvancedAPIs.MailList;
using Senparc.Weixin.Work.Containers;
using WeiXinAPI.Common;
using WeiXinAPI.model;
using Nancy.Extensions;

namespace WeiXinAPI
{
    public class WxReportHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();


        #region 获取用户已授权报表 GetReportList

        [MustLogin]
        [Description("获取用户已授权报表")]
        [ReturnType(typeof(int))]
        public ApiResult GetReportListByUserId(string UserId)
        {
            if (UserId.IsNullOrWhiteSpace())
            {
                return Error("参数异常，请重新再试");
            }

            var dc = new TerminalEntities();
            var list = dc.MemberReport.Where(x => x.UserId == UserId).ToList();
            return Success(list);
        }

        #endregion

        #region 获取报表列表 GetReportList

        [MustLogin]
        [Description("获取报表列表")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult GetReportList(string wxConfig, [ParamDescription("搜索的报表标题")] string conditionTitle = "")
        {
            var wxInfo = WXBaseHandler.TryGetWxCorpInfo(wxConfig);
            if (wxInfo.CorpInfo == null)
            {
                return Error(wxInfo.Message);
            }

            var dc = new TerminalEntities();
            var list = new List<Report>();
            if (conditionTitle.IsNullOrWhiteSpace())
            {
                list = dc.Report.Where(x => x.CIdentification == wxInfo.CorpInfo.CIdentification).ToList();
            }
            else
            {
                list = dc.Report.Where(x => x.CIdentification == wxInfo.CorpInfo.CIdentification && x.Title.Contains(conditionTitle)).ToList();
            }

            return Success(list);
        }

        #endregion

        #region 获取报表列表 GetReportListByCode

        //[MustLogin]
        [Description("获取报表列表")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult GetReportListByCode([ParamDescription("搜索的报表标题")] string Code, string wxConfig)
        {
            try
            {
                var wxInfo = WXBaseHandler.TryGetWxCorpInfo(wxConfig);
                if (wxInfo.CorpInfo == null)
                {
                    return Error(wxInfo.Message);
                }


                var dc = new TerminalEntities();
                var accessToken = AccessTokenContainer.TryGetToken(wxInfo.CorpInfo.CorpID, wxInfo.CorpInfo.CorpSercet);
                //同token和code获取当前用户Id
                var user = OAuth2Api.GetUserId(accessToken, Code);
                var userInfo = MailListApi.GetMember(accessToken, user.UserId);
                var report = (from r in dc.Report
                    join m in dc.MemberReport on r.Id equals m.ReportId
                    where r.CIdentification == wxInfo.CorpInfo.CIdentification &&
                          (wxInfo.CorpInfo.CIdentification == new Guid("F6413A9A-435C-4601-917E-52BAB9DFB3C5") ||
                           m.UserId == user.UserId)
                    select new {r.Id, r.Title, r.Link, m.UserId, m.UserName, r.IconUrl}).DistinctBy(d => d.Id).Select(
                    t => new ReportData
                    {
                        Id = t.Id,
                        UserId = user.UserId,
                        Link = t.Link,
                        Title = t.Title,
                        UserName = userInfo.name,
                        IconUrl = t.IconUrl,
                    }).ToList();

                //获取当前用户可以浏览的报表的Id集合
                //var reportIdList = dc.MemberReport.Where(x => x.UserId == user.UserId).Select(x => x.ReportId)
                //    .ToList();
                //用报表的Id集合获取具体的报表信息
                //var reportList = dc.Report.Where(x => reportIdList.Contains(x.Id)).ToList();
                return Success(report);


            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        #endregion

        #region 获取店铺列表 GetShopList

        [MustLogin]
        [Description("获取店铺列表")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult GetShopList([ParamDescription("搜索的店铺名称")] string shopTitle = "")
        {
            //没有用户传进来，不用考虑IsChecked，直接把完整的表数据根据title丢出去就行
            var shopSql = @"
SELECT (SELECT count(1) 
		FROM ndw.ndw_Shop 
		where CompanyID = 'NM') as 'ShopCount',
* 
FROM ndw.ndw_Shop 
where CompanyID = 'NM'
";
            if (!string.IsNullOrWhiteSpace(shopTitle))
            {
                shopSql += $" and ShopName like '%{shopTitle}%' ";
            }

            //排序
            shopSql += " order by ShopCode ";
            var shopDt = Helper.ExecuteDataTable(Helper.GetSqlStringCommand(shopSql));
            var shopList = ModelConvertHelper<ShopInfo>.ConvertToModel(shopDt);
            return Success(shopList);
        }

        #endregion

        #region 获取用户已关联 GetShopListByUserId

        [MustLogin]
        [Description("获取用户已授权报表")]
        [ReturnType(typeof(int))]
        public ApiResult GetShopListByUserId(string UserId = "", string ShopName = "")
        {
            if (UserId.IsNullOrWhiteSpace())
            {
                return Error("参数异常，请重新再试");
            }

            //有用户传进来,要根据userId判断是否勾选，凡是勾选的，不管是不是符合搜索，都要输出
            var shopSql = $@"
select * 
from (	SELECT isnull((	select true 
						from ntmp.ntmp_nm_franchisee_permission f 
						where f.UserID = '{UserId}' and f.ShopCode=s.ShopCode),false) as IsChecked,s.* 
		FROM ndw.ndw_Shop s 
		where s.CompanyID = 'NM'
	) t 
where IsChecked or ShopName like '%{ShopName}%'
order by t.IsChecked desc,t.ShopCode ";

            var shopDt = Helper.ExecuteDataTable(Helper.GetSqlStringCommand(shopSql));
            var shopList = ModelConvertHelper<ShopInfo>.ConvertToModel(shopDt);
            return Success(shopList);
        }

        #endregion


        #region 设置用户与店铺关联关系 SetMemberShopRelation

        [JsonType]
        [MustLogin]
        [Description("设置用户与报表的关联关系")]
        [ReturnType(typeof(int))]
        public ApiResult SetMemberShopRelation(MemberShopInfo infos)
        {
            if (infos.MemberIdList.Count == 0)
            {
                return Error("请选择要操作的用户");
            }

            var cmdList = new List<CommandInfo>();
            //先删除userID已经有的店铺
            foreach (var user in infos.MemberIdList)
            {
                cmdList.Add(new CommandInfo($"DELETE FROM ntmp.ntmp_nm_franchisee_permission  where UserID = '{user.userId}'; ", null));
            }

            var tList = new List<NmFranchiseePermission>();
            foreach (var user in infos.MemberIdList)
            {
                if (infos.QueryFlag == 1)
                {
                    var item = new NmFranchiseePermission()
                    {
                        UserID = user.userId,
                        UserName = user.userName,
                        ShopCode = "(无)",
                        ShopName = "(无)",
                        QueryFlag = infos.QueryFlag
                    };
                    tList.Add(item);
                }
                else
                {
                    foreach (var shop in infos.ShopList)
                    {
                        var item = new NmFranchiseePermission()
                        {
                            UserID = user.userId,
                            UserName = user.userName,
                            ShopCode = shop.ShopCode,
                            ShopName = shop.ShopName,
                            QueryFlag = infos.QueryFlag
                        };
                        tList.Add(item);
                    }
                }
            }

            try
            {
                var dt = DataTableHelper.LinqToDataTable(tList);
                var n = Helper.ExecuteSqlTran(cmdList, dt, " ntmp.ntmp_nm_franchisee_permission ");
                return Success(n > 0);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion


        #region 企业微信[报表管理]页面方法

        #region 获取报表列表 Report_GetList

        [MustLogin]
        [Description("获取报表列表")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult Report_GetList(string CIdentification = "")
        {
            var guid = Guid.Empty;
            if (!CIdentification.IsNullOrWhiteSpace())
            {
                if (!Guid.TryParse(CIdentification, out guid))
                {
                    return Error("参数异常");
                }
            }

            if (CIdentification.IsNullOrWhiteSpace())
            {
                var list = new TerminalEntities().Report.ToList();
                return Success(list);
            }
            else
            {
                var list = new TerminalEntities().Report.Where(x => x.CIdentification == guid).ToList();
                return Success(list);
            }
        }

        #endregion

        #region 获取报表详情 Report_GetDetail

        [MustLogin]
        [Description("获取报表详情")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult Report_GetDetail(int rId)
        {
            var guid = Guid.Empty;
            if (rId <= -1)
            {
                return Error("参数异常");
            }

            var list = new TerminalEntities().Report.Where(x => x.Id == rId).ToList();
            return Success(list);
        }

        #endregion

        #region 添加报表 Report_Add

        [JsonType]
        [MustLogin]
        [Description("添加报表")]
        [ReturnType(typeof(int))]
        public ApiResult Report_Add(Report report)
        {
            var dc = new TerminalEntities();
            report.CreateTime = DateTime.Now;
            report.UpdateTime = DateTime.Now;
            dc.Report.Add(report);
            var result = dc.SaveChanges();
            return Success(result);
        }

        #endregion

        #region 修改报表 Report_Update

        [JsonType]
        [MustLogin]
        [Description("修改报表")]
        [ReturnType(typeof(int))]
        public ApiResult Report_Update(Report report)
        {
            if (report.Id <= 0)
            {
                return Error("修改失败！找不到对应的报表");
            }

            var dc = new TerminalEntities();
            var model = dc.Report.FirstOrDefault(x => x.Id == report.Id);
            if (model == null)
            {
                return Error("修改失败！找不到对应的报表");
            }

            model.Title = report.Title;
            model.Link = report.Link;
            model.CIdentification = report.CIdentification;
            model.UpdateTime = DateTime.Now;
            model.IconUrl = report.IconUrl;
            var result = dc.SaveChanges();
            return Success(result);
        }

        #endregion

        #region 删除报表 RemoveWxCorpInfo

        [MustLogin]
        [Description("删除报表")]
        [ReturnType(typeof(int))]
        public ApiResult Report_Delete(int Id)
        {
            if (Id <= 0)
            {
                return Error("参数异常，请重新再试");
            }

            var dc = new TerminalEntities();
            var model = dc.Report.FirstOrDefault(x => x.Id == Id);
            if (model != null)
            {
                dc.Report.Remove(model);
                var result = dc.SaveChanges();
                return Success(result);
            }
            return Error("删除失败！找不到对应的报表信息");
        }

        #endregion

        #endregion
        
        //[MustLogin]
        [Description("获取图标地址")]
        [ReturnType(typeof(IList<string>))]
        public ApiResult GetIconUrl()
        {
            try
            {
                var strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                if (!Directory.Exists(strPath + "WeixinWork"))
                {
                    return Error("图标目录不存在!");
                }
                if (!Directory.Exists(strPath + "WeixinWork\\Icon"))
                {
                    return Error("图标目录不存在!");
                }
                var dyInfo = new DirectoryInfo(strPath + "WeixinWork\\Icon");
                var result = new List<string>();
                //获取文件夹下所有的文件
                foreach (FileInfo feInfo in dyInfo.GetFiles())
                {
                    result.Add($@"WeixinWork\Icon\{feInfo.Name}");
                }
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
    }
}
